<template>
  <div class="upload-container">
    <van-form @failed="onFailed" @submit="onSubmit">
      <van-cell-group class="h-group" inset>
         <van-field
            v-model="formData.description"
            rows="2"
            name="description"
            autosize
            label="描述"
            type="textarea"
            maxlength="100"
            placeholder="请输入详细信息"
            :rules="[{ required: true, message: '请输入详细信息' }]"
            show-word-limit
          />
      </van-cell-group>
      <van-cell-group class="h-group" style="margin-top: 16px;" inset>
         <van-field name="images" :label="`现场照片(${formData.images.length}/9)`" :rules="[{ validator: validatorImages }]" :preview-image="false">
          <template #input>
            <van-uploader max-count="9" v-model="formData.images" :after-read="afterRead" multiple :max-size="15 * 1024 * 1024" @oversize="onOversize" />
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group style="margin-top: 16px;" inset>
         <!-- <van-field name="problemAddress" @click="showMap" v-model="formData.problemAddress" label="问题地址" placeholder="请在地图上选择地址" readonly :rules="[{ required: true, message: '请在地图上选择地址' }]" /> -->
         <van-field name="addressInfo" v-model="formData.addressInfo" label="详细地址" placeholder="最多不能超过16个字" :rules="[{ required: true, message: '请输入详细地址' }]" />
         <van-field name="contacts" v-model="formData.contacts" label="联系人" placeholder="最多不能超过16个字" :rules="[{ required: true, message: '请输入联系人' }]" />
         <van-field name="phone" v-model="formData.phone" label="联系方式" placeholder="最多不能超过16个字" :rules="[{ required: true, message: '请输入联系方式' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <van-dialog v-model:show="visible" title="选择地址" show-cancel-button @confirm="confirmDialog">
      <div style="width: 100%;height: 70vh">
        <iframe id="mapPage" width="100%" height="100%" frameborder=0 src="https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&key=MD3BZ-4VRKW-UKQRQ-R2BVR-2JPXZ-WXFPA&referer=myapp"></iframe>
      </div>
    </van-dialog>
  </div>
</template>
<script>
import { reactive, ref, toRaw } from 'vue'
// import axios from 'axios'
import request from '@utils/request'
import { Toast } from 'vant'
import COS from 'cos-js-sdk-v5'
// 初始化实例
let sessionToken
const cos = new COS({
  // getAuthorization 必选参数
  getAuthorization: function (options, callback) {
    const url = 'http://qs.letterchain.cn/api/cos/getCredential'
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.onload = function (e) {
      let data
      let credentials
      try {
        data = JSON.parse(e.target.responseText)
        credentials = data.data
      } catch (e) {}
      if (!data || !credentials) {
        return console.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
      };
      const cosObj = {
        TmpSecretId: credentials.credentials.tmpSecretId,
        TmpSecretKey: credentials.credentials.tmpSecretKey,
        SecurityToken: credentials.credentials.sessionToken,
        StartTime: credentials.startTime,
        ExpiredTime: credentials.expiredTime
      }
      console.log(cosObj)
      callback(cosObj)
    }
    xhr.send()
  }
})
const Bucket = 'qushui-1251030455'
const Region = 'ap-shanghai'

export default {
  setup () {
    const formData = reactive({
      description: '',
      images: [],
      problemAddress: '',
      addressInfo: '',
      contacts: '',
      phone: ''
    })
    const visible = ref(false)
    const location = ref(null)
    // 上传图片
    const upload = (file) => {
      return new Promise((resolve, reject) => {
        cos.putObject({
          Bucket,
          Region,
          Key: 'qushui/' + file.name,
          Body: file,
          Headers: {
            'x-cos-security-token': sessionToken
          },
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData))
          }
        }, function (err, data) {
          if (data) {
            resolve(`${window.location.protocol}//${data.Location}`)
          } else {
            reject(err)
          }
        })
      })
    }
    const afterRead = (file) => {
      // 此时可以自行将文件上传至服务器
      const num = Number(file.length)
      if (num > 0) {
        for (let i = 0; i < num; i++) {
          file[i].status = 'uploading'
          file[i].messasge = '上传中...'
          upload(toRaw(file)[i].file).then(url => {
            file[i].status = 'success'
            file[i].url = url
          })
        }
      } else {
        file.status = 'uploading'
        file.messasge = '上传中...'
        upload(toRaw(file).file).then(url => {
          file.status = 'success'
          file.url = url
        })
      }
    }

    const onFailed = (errorInfo) => {
      console.log('failed', errorInfo)
    }

    // 校验
    const validatorImages = (val) => {
      if (formData.images.length <= 0) return '请上传图片'
    }
    const onOversize = file => {
      Toast('文件大小不能超过 15MB')
    }
    return {
      formData,
      onFailed,
      onOversize,
      visible,
      location,
      afterRead,
      validatorImages
    }
  },
  methods: {
    onSubmit (values) {
      request.post('/photo/add', {
        ...values,
        images: [...this.formData.images].map(col => col.url).join(',')
      }).then(resp => {
        console.log(resp)
        Toast('保存成功')
        this.$router.push('/')
      })
    },
    showMap () {
      this.location = null
      this.visible = true
    },
    getLocation (event) {
      this.location = event.data
    },
    confirmDialog () {
      this.formData.problemAddress = this.location.poiaddress
    }
  },
  mounted () {
    window.addEventListener('message', this.getLocation, false)
  },
  beforeUnmount () {
    window.removeEventListener('message', this.getLocation, false)
  }
}
</script>
<style lang="less" scoped>
.upload-container {
  padding-top: 16px;
  .h-group {
    .van-cell {
      display: block;
    }
  }
}
</style>
